package cn.jjxx.core.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import cn.jjxx.shiro.httpclient.Response;
import cn.jjxx.shiro.httpclient.utils.HttpUtil;
import net.sf.json.JSONObject;

public class HttpClientUtils {
	/*static CloseableHttpClient client = null;
	static { 
		RequestConfig defaultRequestConfig = RequestConfig.custom()
				.setSocketTimeout(50000)
				.setConnectTimeout(50000)
				.setConnectionRequestTimeout(30000)
				.build();

		client = HttpClients.custom()
				.setDefaultRequestConfig(defaultRequestConfig)
				.build(); 
	}*/


	/**
	 * 接口参数
	 *@Title HttpClientUtils.java
	 *@description TODO
	 *@time 2021年11月4日 上午11:37:07
	 *@author YAOXIONG
	 *@version 1.0
	 *
	 */
	public static JSONObject jsonGet(String url){

		try {
			return jsonGet(url,null);
		}catch (Exception e){ 
		}
		return null;
	} 

	
	public static JSONObject jsonGet(String url,String entityJson ){

		try { 
			/*RestTemplate restTemplate = new RestTemplate();  
			HttpHeaders headers = new HttpHeaders();
			MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
			headers.setContentType(type);
			headers.add("Accept", MediaType.APPLICATION_JSON.toString());
			HttpEntity<String> formEntity = new HttpEntity<String>(entityJson, headers);

			JSONObject jsonObject= restTemplate.postForObject(url,formEntity,JSONObject.class);  
*/
			JSONObject jsonObject= doGet(url);
			return jsonObject;
		}catch (Exception e){ 
		}
		return null;
	} 
	private static Logger log = LoggerFactory.getLogger("HttpClientUtils");
	@SuppressWarnings({ "deprecation", "resource" })
	public static JSONObject doGet(String url){
		try {
			//HttpClient client = new DefaultHttpClient();
			//发送get请求
			/*HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			*//**请求发送成功，并得到响应**//*
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				*//**读取服务器返回过来的json字符串数据**//*
				String result = EntityUtils.toString(response.getEntity(),"UTF-8");
				return JSONObject.fromObject(result);
			}*/
			HttpClient client = new DefaultHttpClient();
			//发送get请求
			HttpGet request = new HttpGet(url);
			RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
			request.setConfig(requestConfig);
			HttpResponse response = client.execute(request);
			/**请求发送成功，并得到响应**/
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				/**读取服务器返回过来的json字符串数据**/
				String result = EntityUtils.toString(response.getEntity());
				return JSONObject.fromObject(result);
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
			log.info("-----请求超时--------"+url);
		}
		return new JSONObject();
	}

	@SuppressWarnings({ "deprecation", "resource" })
	public static JSONObject doHttpGet(String url){
		HttpClient httpClient = new DefaultHttpClient();
		try {
			httpClient.getParams().setParameter("http.connection.timeout", 10000);
			HttpGet get = new HttpGet(url);
			HttpResponse rp = httpClient.execute(get);
			Response r = HttpUtil.convert(rp);
			/**请求发送成功，并得到响应**/
			if (r.getStatusCode() == HttpStatus.SC_OK) {
				/**读取服务器返回过来的json字符串数据**/
				String result = r.getBody();
				return JSONObject.fromObject(result);
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (httpClient != null) {
				httpClient.getConnectionManager().shutdown();
			}
		}
		return new JSONObject();
	}


	public synchronized static JSONObject doPost(String url, Map<String,Object> params){
		BufferedReader in = null;  
		try {  
			// 定义HttpClient  
			//HttpClient client = new DefaultHttpClient();
			/*RequestConfig defaultRequestConfig = RequestConfig.custom()
					.setSocketTimeout(10000)
					.setConnectTimeout(10000)
					.setConnectionRequestTimeout(10000) 
					.build();

			CloseableHttpClient client = HttpClients.custom()
					.setDefaultRequestConfig(defaultRequestConfig)
					.build(); 
			// 实例化HTTP方法  
			HttpPost post = new HttpPost();  
			post.setURI(new URI(url));

			//设置参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 
			for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String value = String.valueOf(params.get(name));
				nvps.add(new BasicNameValuePair(name, value));
			}
			post.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
			RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(20000).
					setConnectTimeout(50000).setConnectionRequestTimeout(5000).build();
			post.setConfig(requestConfig);
			HttpResponse response = client.execute(post);  
			int code = response.getStatusLine().getStatusCode();
			if(code == 200){	//请求成功
				in = new BufferedReader(new InputStreamReader(response.getEntity()  
						.getContent(),"utf-8"));
				StringBuffer sb = new StringBuffer("");  
				String line = "";  
				String NL = System.getProperty("line.separator");  
				while ((line = in.readLine()) != null) {  
					sb.append(line + NL);  
				}
				in.close();  
				return JSONObject.fromObject(sb.toString());
			}*/
			// 定义HttpClient
			HttpClient client = new DefaultHttpClient();
			// 实例化HTTP方法
			HttpPost post = new HttpPost();
			post.setURI(new URI(url));

			//设置参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String value = String.valueOf(params.get(name));
				nvps.add(new BasicNameValuePair(name, value));
			}
			post.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
			RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
			post.setConfig(requestConfig);
			HttpResponse response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if(code == 200){	//请求成功
				in = new BufferedReader(new InputStreamReader(response.getEntity()
						.getContent(),"utf-8"));
				StringBuffer sb = new StringBuffer("");
				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}
				in.close();
				return JSONObject.fromObject(sb.toString());
			}

		}catch(Exception e){
			e.printStackTrace();
		}
		return new JSONObject();
	}
}
